package com.emp.util;

import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.emp.bean.User;
import com.emp.service.UserService;

//编写一个自定义的Realm基础shiro插件提供AuthorizingRealm
public class MyRealm extends AuthorizingRealm {
	 
	public MyRealm(){
		setCredentialMatcher();
	}
	@Resource
	private UserService userService;
 
	/**
	 * 授权方法
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		/**
		 * 注意principals.getPrimaryPrincipal()对应
		 * new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName())的第一个参数
		 */
		//获取当前身份
		String userName = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		//从数据库中查找该用户有何角色和权限
		Set<String> roles = userService.getRoles(userName);
		Set<String> permissions = userService.getPermissions(userName);
		
		//为当前用户赋予对应角色和权限
		info.setRoles(roles);
	    info.setStringPermissions(permissions);
		
		return info;
	}
 
	/**
	 * 认证方法--登录业务
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		//获取用户名
		String username = (String) token.getPrincipal();
		
		//从数据库中查找用户信息
		User user;
		try {
			//从数据库中查询出user对象
		    user = userService.queryUserByName(username);
		    //user = new User();
		    //user.setPassword("2df1318ab2463f460507925903c97cc2");
		    //user.setUsername("888");
		    //user.setSalt("Tocg");
		} catch (Exception e) {
			e.printStackTrace();
			throw new AuthenticationException(e);
		}
		
		if (user == null) {//用户名错误
			return null;			
		}
		
		SimpleAuthenticationInfo  info 
		= new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), getName());
		info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
		return info;
	}
	
	public String getName(){
		return "MyRealm";
	}
	
	 //方法初始化配置
	 public void setCredentialMatcher(){
	        HashedCredentialsMatcher  credentialsMatcher = new HashedCredentialsMatcher();    
	        credentialsMatcher.setHashAlgorithmName("md5");//MD5算法加密
	        credentialsMatcher.setHashIterations(1);//1次循环加密      
	        setCredentialsMatcher(credentialsMatcher);
	 }
 
}

